import { TouchHandle } from "../../../core/data_ext";
import { SubjectComponent } from "../../../core/subject";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MutiTouch extends SubjectComponent {
    touches: TouchHandle[] = [];
    touchDis = 0;

    protected _onTouchStart(evt: cc.Event.EventTouch) {
        let loc = evt.getLocation();
        let id = evt.getID();

        let touch = this.touches.find(ele => ele.id == evt.getID());
        if (!touch) {
            touch = new TouchHandle(id);
            this.touches.push(touch);
        }
        touch.loc = loc
        touch.delta = cc.v2();

        if (this.touches.length > 1) {
            let t1 = this.touches[0];
            let t2 = this.touches[1];
            this.touchDis = t1.loc.sub(t2.loc).mag();
        }
        this.emit("start", touch);
        this.onTouchStart(touch);
    }
    protected _onTouchMove(evt: cc.Event.EventTouch) {
        let loc = evt.getLocation();
        let delta = evt.getDelta();
        let id = evt.getID();
        let touch = this.touches.find(ele => ele.id == evt.getID());
        if (!touch) {
            touch = new TouchHandle(id);
            this.touches.push(touch);
        }
        touch.dis += delta.len();
        touch.loc = loc;
        touch.delta = delta;
        if (this.touches.length > 1) {
            let t1 = this.touches[0];
            let t2 = this.touches[1];
            let dis = t1.loc.sub(t2.loc).mag();
            this.touchDis = dis;
            this.emit("muti-move", this.touches);
            this.onTouchMutiMove(this.touches);
        }
        else {
            this.emit("single-move", touch);
            this.onTouchSingleMove(touch);
        }
        this.emit("move", touch);
        this.onTouchMove(touch);
    }
    protected _onTouchEnd(evt: cc.Event.EventTouch) {
        let id = evt.getID();
        let foundInd = this.touches.findIndex(ele => ele.id == id);
        if (foundInd !== -1) {
            let handle = this.touches.splice(foundInd, 1)[0];
            this.emit("end", handle);
            this.onTouchEnd(handle)
        }
        this.touchDis = 0;
    }
    onTouchStart(handle: TouchHandle) {
    }
    onTouchMove(handle: TouchHandle) {
    }
    onTouchSingleMove(handle: TouchHandle) {
    }
    onTouchMutiMove(handles: TouchHandle[]) {
    }
    onTouchEnd(handle: TouchHandle) {
    }

    protected onEnable(): void {
        this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
    }
    protected onDisable(): void {
        this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchStart, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnd, this);
    }
};